package com.basic.library.utils

import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.URLSpan
import android.widget.TextView
import androidx.annotation.NonNull

/**
 * @author yj
 * @description
 */
object TextViewUtils {

    /**
     * 自定义超链接点击事件
     * 传入TextView ，text已经是Html形式
     */
    fun setMyClickableSpan(textView: TextView, text: Spanned, @NonNull clickableSpan: ClickableSpan) {
        textView.movementMethod = LinkMovementMethod.getInstance()
        if (text is Spannable) {
            val end = text.length
            val sp = text as Spannable  //构建Spannable对象、继承Spanned、Spanned对象继承CharSequener
            val urls = sp.getSpans(0, end, URLSpan::class.java)
            val style = SpannableStringBuilder(text)
            style.clearSpans()
            urls.forEach {
                //设置样式其中参数what是具体样式的实现对象，start则是该样式开始的位置，end对应的是样式结束的位置，
                // 参数 flags，定义在Spannable中的常量
                style.setSpan(clickableSpan, sp.getSpanStart(it), sp.getSpanEnd(it), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            textView.text = style
        }
    }
}